<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>爱国情感批量分析</title>
    <link rel="stylesheet" href="/static/css/layui.css">
    <script src="/static/jquery-3.6.0.min.js"></script>
    <script src="/static/layui.js"></script>
    <style>
        body {
            background-color: #f5f5f5;
            font-family: 'Microsoft YaHei', sans-serif;
        }

        .progress-container {
            margin: 20px 0;
            display: none;
        }

        .result-container {
            margin-top: 20px;
            display: none;
        }
    </style>
</head>

<body>
    <div class="layui-container" style="padding: 20px;">
        <div class="layui-row">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-header">
                        <h2>爱国情感批量分析</h2>
                        <p style="color: #666; margin-top: 10px;">
                            <i class="layui-icon layui-icon-tips" style="color: #01AAED;"></i>
                            注意：爱国情感分析仅支持文本类型的作业，以下列表只显示文本作业
                        </p>
                    </div>
                    <div class="layui-card-body">
                        <form class="layui-form" id="batchAnalyzeForm">
                            <div class="layui-form-item">
                                <label class="layui-form-label">选择作业：</label>
                                <div class="layui-input-block">
                                    <select name="homework_id" lay-verify="required" lay-search>
                                        <option value="">请选择要分析的文本作业</option>
                                        {% for homework in homeworks %}
                                        <option value="{{ homework.ID }}">{{ homework.title }} (文本作业)</option>
                                        {% endfor %}
                                    </select>
                                    {% if not homeworks %}
                                    <div class="layui-form-mid layui-word-aux" style="color: #FF5722;">
                                        暂无文本类型的作业可供分析，请先创建文本作业。
                                    </div>
                                    {% endif %}
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">分析模式：</label>
                                <div class="layui-input-block">
                                    <select name="prompt_type" lay-verify="required">
                                        <option value="standard">标准分析 - 基础爱国情感分析</option>
                                        <option value="detailed">详细分析 - 五维度深入分析</option>
                                        <option value="educational">教育导向 - 教育角度分析</option>
                                        <option value="comprehensive">综合分析 - 最全面的分析模式</option>
                                    </select>
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="batchAnalyze">
                                        <i class="layui-icon layui-icon-search"></i> 开始批量分析
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-normal" id="viewResults">
                                        <i class="layui-icon layui-icon-chart"></i> 查看图表统计
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-warm"
                                        onclick="window.location.href='/patriotic_prompt/'">
                                        <i class="layui-icon layui-icon-return"></i> 返回主页
                                    </button>
                                </div>
                            </div>
                        </form>

                        <!-- 分析进度 -->
                        <div id="progressContainer" style="display: none;">
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    <h3>分析进度</h3>
                                </div>
                                <div class="layui-card-body">
                                    <div class="layui-progress layui-progress-big" lay-showpercent="true">
                                        <div class="layui-progress-bar" lay-percent="0%"></div>
                                    </div>
                                    <div id="progressText" style="text-align: center; margin-top: 10px;">
                                        准备分析...
                                    </div>
                                    <div id="currentStudent" style="text-align: center; margin-top: 5px; color: #666;">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 分析结果 -->
                        <div id="resultsContainer" style="display: none;">
                            <div class="layui-card">
                                <div class="layui-card-header">
                                    <h3>分析结果统计</h3>
                                </div>
                                <div class="layui-card-body">
                                    <div class="layui-row">
                                        <div class="layui-col-md3">
                                            <div class="layui-card">
                                                <div class="layui-card-body" style="text-align: center;">
                                                    <h4>总数量</h4>
                                                    <p id="totalCount" style="font-size: 24px; color: #1E9FFF;">0</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="layui-col-md3">
                                            <div class="layui-card">
                                                <div class="layui-card-body" style="text-align: center;">
                                                    <h4>成功数量</h4>
                                                    <p id="successCount" style="font-size: 24px; color: #5FB878;">0</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="layui-col-md3">
                                            <div class="layui-card">
                                                <div class="layui-card-body" style="text-align: center;">
                                                    <h4>失败数量</h4>
                                                    <p id="errorCount" style="font-size: 24px; color: #FF5722;">0</p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="layui-col-md3">
                                            <div class="layui-card">
                                                <div class="layui-card-body" style="text-align: center;">
                                                    <h4>操作</h4>
                                                    <button class="layui-btn layui-btn-sm" id="exportResults">
                                                        <i class="layui-icon layui-icon-download-circle"></i> 导出结果
                                                    </button>
                                                    <button class="layui-btn layui-btn-sm layui-btn-normal"
                                                        id="viewDetailedResults">
                                                        <i class="layui-icon layui-icon-file-b"></i> 详细分析
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 结果表格 -->
                            <div class="layui-card" style="margin-top: 20px;">
                                <div class="layui-card-header">
                                    <h3>详细分析结果</h3>
                                </div>
                                <div class="layui-card-body">
                                    <table class="layui-table" lay-skin="line">
                                        <thead>
                                            <tr>
                                                <th>学生姓名</th>
                                                <th>学号</th>
                                                <th>班级</th>
                                                <th>状态</th>
                                                <th>爱国情感得分</th>
                                                <th>爱国情感等级</th>
                                                <th>评分</th>
                                                <th>置信度</th>
                                                <th>详细信息</th>
                                            </tr>
                                        </thead>
                                        <tbody id="resultsTableBody">
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        layui.use(['form', 'layer', 'element'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var element = layui.element;

            var currentHomeworkId = null;
            var currentPromptType = null;

            // 批量分析表单提交
            form.on('submit(batchAnalyze)', function (data) {
                var homeworkId = data.field.homework_id;
                var promptType = data.field.prompt_type;

                if (!homeworkId) {
                    layer.msg('请选择要分析的作业', { icon: 2 });
                    return false;
                }

                currentHomeworkId = homeworkId;
                currentPromptType = promptType;

                // 显示进度条
                $('#progressContainer').show();
                $('#resultsContainer').hide();
                $('#progressText').text('正在分析中...');
                $('#currentStudent').text('');

                // 发送分析请求
                $.ajax({
                    url: '/patriotic_prompt/batch_analyze',
                    type: 'POST',
                    data: data.field,
                    success: function (res) {
                        if (res.success) {
                            showResults(res);
                            layer.msg('批量分析完成！', { icon: 1 });
                        } else {
                            layer.msg(res.error || '分析失败', { icon: 2 });
                        }
                    },
                    error: function () {
                        layer.msg('网络错误，请重试', { icon: 2 });
                    },
                    complete: function () {
                        $('#progressContainer').hide();
                    }
                });

                return false;
            });

            // 显示分析结果
            function showResults(data) {
                $('#totalCount').text(data.total_count);
                $('#successCount').text(data.success_count);
                $('#errorCount').text(data.error_count);

                var tbody = $('#resultsTableBody');
                tbody.empty();

                data.results.forEach(function (result) {
                    var row = '<tr>';
                    row += '<td>' + result.student_name + '</td>';
                    row += '<td>' + (result.student_id || '-') + '</td>';
                    row += '<td>' + (result.class_id || '-') + '</td>';

                    if (result.status === 'success') {
                        row += '<td><span class="layui-badge layui-bg-green">成功</span></td>';
                        row += '<td>';
                        row += '<div class="layui-progress layui-progress-sm" lay-showpercent="true">';
                        row += '<div class="layui-progress-bar" lay-percent="' + (result.patriotic_score * 100).toFixed(1) + '%"></div>';
                        row += '</div>';
                        row += '</td>';

                        // 根据等级显示不同颜色的标签
                        var levelClass = '';
                        if (result.patriotic_level === "非常强烈爱国情感") {
                            levelClass = 'layui-bg-red';
                        } else if (result.patriotic_level === "较强爱国情感") {
                            levelClass = 'layui-bg-orange';
                        } else if (result.patriotic_level === "一般爱国情感") {
                            levelClass = 'layui-bg-blue';
                        } else if (result.patriotic_level === "较弱爱国情感") {
                            levelClass = 'layui-bg-gray';
                        }

                        row += '<td><span class="layui-badge ' + levelClass + '">' + result.patriotic_level + '</span></td>';

                        // 根据评分显示不同颜色
                        var gradeColor = '';
                        if (result.grade >= 90) {
                            gradeColor = '#5FB878';
                        } else if (result.grade >= 80) {
                            gradeColor = '#FFB800';
                        } else if (result.grade >= 60) {
                            gradeColor = '#FF5722';
                        } else {
                            gradeColor = '#999';
                        }

                        row += '<td><span style="color: ' + gradeColor + '; font-weight: bold;">' + result.grade + '</span></td>';
                        row += '<td>' + (result.confidence * 100).toFixed(1) + '%</td>';
                        row += '<td>';
                        row += '<button class="layui-btn layui-btn-xs" onclick="showDetail(\'' + result.student_name + '\', \'' + result.patriotic_level + '\', \'' + result.patriotic_score + '\', \'' + result.patriotic_words_count + '\', \'' + result.anti_patriotic_words_count + '\', \'' + result.model_type + '\')">';
                        row += '查看详情</button>';
                        row += '</td>';
                    } else {
                        row += '<td><span class="layui-badge layui-bg-red">失败</span></td>';
                        row += '<td colspan="4">-</td>';
                        row += '<td>' + result.message + '</td>';
                    }

                    row += '</tr>';
                    tbody.append(row);
                });

                $('#resultsContainer').show();

                // 重新渲染进度条
                element.render('progress');
            }

            // 查看分析结果
            $('#viewResults').click(function () {
                var homeworkId = $('select[name="homework_id"]').val();
                if (!homeworkId) {
                    layer.msg('请先选择作业', { icon: 2 });
                    return;
                }

                window.open('/patriotic_prompt/analysis_results/' + homeworkId, '_blank');
            });

            // 查看详细结果
            $('#viewDetailedResults').click(function () {
                if (!currentHomeworkId) {
                    layer.msg('请先进行批量分析', { icon: 2 });
                    return;
                }

                console.log('点击详细分析按钮，跳转到：', '/patriotic_prompt/detailed_analysis/' + currentHomeworkId);
                var url = '/patriotic_prompt/detailed_analysis/' + currentHomeworkId + '?t=' + new Date().getTime();
                window.open(url, '_blank');
            });

            // 导出结果
            $('#exportResults').click(function () {
                if (!currentHomeworkId) {
                    layer.msg('请先进行批量分析', { icon: 2 });
                    return;
                }

                layer.msg('正在生成导出文件...', { icon: 16, time: 0 });

                $.get('/patriotic_prompt/export_results/' + currentHomeworkId, function (res) {
                    layer.closeAll();
                    if (res.success) {
                        // 创建下载链接
                        var link = document.createElement('a');
                        link.href = res.download_url;
                        link.download = '';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        layer.msg('导出成功！', { icon: 1 });
                    } else {
                        layer.msg('导出失败', { icon: 2 });
                    }
                });
            });

            // 显示详细信息
            window.showDetail = function (studentName, level, score, patrioticWords, antiPatrioticWords, modelType) {
                var content = `
                <div style="padding: 20px;">
                    <h4>${studentName} 的爱国情感分析详情</h4>
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <p><strong>学生姓名：</strong>${studentName}</p>
                            <p><strong>爱国情感等级：</strong>${level}</p>
                            <p><strong>爱国情感得分：</strong>${(score * 100).toFixed(1)}%</p>
                            <p><strong>爱国词汇数量：</strong>${patrioticWords}</p>
                        </div>
                        <div class="layui-col-md6">
                            <p><strong>反爱国词汇数量：</strong>${antiPatrioticWords}</p>
                            <p><strong>分析模型：</strong>${modelType}</p>
                            <p><strong>分析时间：</strong>${new Date().toLocaleString()}</p>
                        </div>
                    </div>
                </div>
            `;

                layer.open({
                    type: 1,
                    title: '分析详情',
                    area: ['600px', '400px'],
                    content: content
                });
            };
        });
    </script>
</body>

</html>